import React, { useState, useEffect, useRef } from 'react';
import {
  ArrowLeftOutlined,
  HeartOutlined,
  ClockCircleOutlined,
  UserOutlined,
  EnvironmentOutlined,
  StarOutlined,
  CheckCircleOutlined,
  LoadingOutlined,
  AlertOutlined
} from '@ant-design/icons';
import { message } from 'antd';
import { Button, Rate, Toast, Skeleton, Dialog } from 'antd-mobile';
import { useParams, useNavigate } from 'react-router-dom';
import './ProjectDetail.css';
import { get_single_product_package, get_products, add_appointment } from "../../services/product";
import Error from '../../components/Error';
import Loaging from '../../components/Loading';
import { useSelector } from 'react-redux';

// 轮播图组件（保持不变）
const Carousel = ({ images }) => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const carouselRef = useRef(null);

  useEffect(() => {
    const interval = setInterval(() => {
      setCurrentIndex((prev) => (prev + 1) % images.length);
    }, 5000);
    return () => clearInterval(interval);
  }, [images.length]);

  const handleDotClick = (index) => {
    setCurrentIndex(index);
  };

  return (
    <div className="carousel-container">
      <div
        ref={carouselRef}
        className="carousel-track"
        style={{ transform: `translateX(-${currentIndex * 100}%)` }}
      >
        {images.map((img, index) => (
          <div key={index} className="carousel-slide">
            <img
              src={img}
              alt={`项目图片 ${index + 1}`}
              className="carousel-img"
              onError={(e) => e.target.src = 'https://picsum.photos/id/1005/800/500'}
            />
          </div>
        ))}
      </div>
      <div className="carousel-dots">
        {images.map((_, index) => (
          <span
            key={index}
            className={`carousel-dot ${index === currentIndex ? 'active' : ''}`}
            onClick={() => handleDotClick(index)}
            aria-label={`查看第${index + 1}张图片`}
          />
        ))}
      </div>
    </div>
  );
};

// 服务流程组件（保持不变）
const ServiceProcess = ({ steps, loading, error }) => {
  if (error) {
    return (
      <div className="service-error">
        <AlertOutlined className="error-icon" />
        <p className="error-message">{error}</p>
        <Button
          className="retry-button"
          variant="outline"
          onClick={() => window.location.reload()}
        >
          重试
        </Button>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="service-loading">
        {[1, 2, 3].map((item) => (
          <div key={item} className="loading-item">
            <Skeleton title={false} paragraph={{ rows: 2 }} />
          </div>
        ))}
      </div>
    );
  }

  if (!steps || steps.length === 0) {
    return (
      <div className="service-empty">
        <p>暂无服务内容信息</p>
      </div>
    );
  }

  return (
    <div className="service-process">
      {steps.map((step, index) => (
        <div key={step.detailId || index} className="process-item">
          <div className="process-number">
            <CheckCircleOutlined className="process-icon" style={{ fontSize: '16px' }} />
          </div>
          <div className="process-content">
            <h4 className="process-title">{step.productName}</h4>
            <p className="process-desc">{step.productEffect || step.remark || '无详细描述'}</p>
            {step.singlePrice && (
              <span className="process-price">¥{step.singlePrice.toFixed(2)}</span>
            )}
          </div>
          {index < steps.length - 1 && <div className="process-line"></div>}
        </div>
      ))}
    </div>
  );
};

// 适用人群组件（保持不变）
const SuitablePeople = ({ people }) => {
  return (
    <div className="suitable-people">
      {people.map((item, index) => (
        <div key={index} className="people-item">
          <div className="people-icon">{item.icon}</div>
          <span className="people-text">{item.text}</span>
        </div>
      ))}
    </div>
  );
};

// 主组件
const ProjectDetail = () => {
  // 状态管理（保持不变）
  const [isFavorite, setIsFavorite] = useState(false);
  const [selectedDateIndex, setSelectedDateIndex] = useState(0);
  const [selectedTime, setSelectedTime] = useState(null);
  const [dates, setDates] = useState([]);
  const [availableTimeSlots, setAvailableTimeSlots] = useState([]);
  const [canBook, setCanBook] = useState(false);
  const [packageData, setPackageData] = useState(null);
  const [serviceContent, setServiceContent] = useState([]);
  const [serviceLoading, setServiceLoading] = useState(false);
  const [serviceError, setServiceError] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [bookingLoading, setBookingLoading] = useState(false);

  // 路由相关（保持不变）
  const params = useParams();
  const { id } = params;
  const navigate = useNavigate();

  // 修复：从Redux正确获取用户信息 - 根据控制台信息调整路径
  // 直接获取login状态，因为控制台显示用户信息存储在login对象中
  const loginState = useSelector(state => state.login);
  const userInfo = loginState?.userInfo;


  // 时间段数据
  const baseTimeSlots = [
    "09:00-12:00",
    "12:00-14:00",
    "14:00-17:00",
    "17:00-18:00",
    "18:00-21:00"
  ];

  // 从接口获取套餐详情
  useEffect(() => {
    const fetchPackageDetail = async () => {
      if (!id) {
        setError("未找到项目ID");
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        const response = await get_single_product_package(id);

        if (response.code === 0) {
          setPackageData(response.data);
          setError(null);
        } else {
          setError(response.msg || "获取项目详情失败");
        }
      } catch (err) {
        console.error("获取套餐详情失败:", err);
        setError("网络错误，无法加载项目详情");
      } finally {
        setLoading(false);
      }
    };

    fetchPackageDetail();
  }, [id]);

  // 从接口获取服务内容
  useEffect(() => {
    if (!id) return;

    const fetchServiceContent = async () => {
      try {
        setServiceLoading(true);
        setServiceError(null);

        const response = await get_products(id);

        if (response.code === 0) {
          setServiceContent(response.data || []);
        } else {
          setServiceContent([]);
          setServiceError(response.msg || "获取服务内容失败");
          Toast.show(response.msg || "获取服务内容失败");
        }
      } catch (err) {
        console.error("获取服务内容失败:", err);
        setServiceContent([]);
      } finally {
        setServiceLoading(false);
      }
    };

    fetchServiceContent();
  }, [id]);

  // 计算未来7天日期
  useEffect(() => {
    const calculateDates = () => {
      const result = [];
      const today = new Date();
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

      for (let i = 0; i < 7; i++) {
        const date = new Date(today);
        date.setDate(today.getDate() + i);

        let weekdayLabel = '';
        if (i === 0) weekdayLabel = '今天';
        else if (i === 1) weekdayLabel = '明天';
        else if (i === 2) weekdayLabel = '后天';
        else weekdayLabel = weekdays[date.getDay()];

        result.push({
          weekday: weekdayLabel,
          day: `${date.getMonth() + 1}/${date.getDate()}`,
          name: weekdays[date.getDay()],
          fullDate: date,
          isPast: i < 0
        });
      }

      setDates(result);
    };

    calculateDates();
  }, []);

  // 根据选中日期过滤可用时段
  useEffect(() => {
    if (dates.length === 0) return;

    const currentDate = dates[selectedDateIndex];
    const isToday = selectedDateIndex === 0;
    const currentHour = new Date().getHours();

    const filteredSlots = baseTimeSlots.filter((slot) => {
      if (!isToday) return true;

      const slotStartHour = parseInt(slot.split('-')[0].split(':')[0]);
      return slotStartHour >= currentHour;
    });

    setAvailableTimeSlots(filteredSlots);
    if (selectedTime !== null && !filteredSlots.includes(baseTimeSlots[selectedTime])) {
      setSelectedTime(null);
    }
  }, [selectedDateIndex, dates]);

  // 检查是否可以预约
  useEffect(() => {
    setCanBook(!!dates[selectedDateIndex] && selectedTime !== null);
  }, [selectedDateIndex, selectedTime, dates]);

  // 处理日期选择
  const handleDateSelect = (index) => {
    if (dates[index]?.isPast) {
      Toast.show('不能选择过去的日期');
      return;
    }
    setSelectedDateIndex(index);
  };

  // 处理时间选择
  const handleTimeSelect = (index) => {
    setSelectedTime(index);
  };

  const handleConfirmBooking = async () => {
    // 登录状态验证
    if (!loginState || !userInfo || !userInfo.id) {
      console.log('登录验证失败，跳转到登录页');
      Toast.show('请先登录');
      navigate('/login', { state: { from: `/project/${id}` } });
      return;
    }

    if (!packageData) return;
    if (selectedTime === null) {
      Toast.show('请选择预约时段');
      return;
    }

    // 验证用户手机号
    if (!userInfo.account || userInfo.account.length !== 11) {
      const phone = prompt('请输入您的手机号码以便预约');
      if (!phone || phone.length !== 11) {
        Toast.show('请输入有效的11位手机号码');
        return;
      }
    }
    setBookingLoading(true);
    // 获取选中的日期
    const selectedDate = new Date(dates[selectedDateIndex].fullDate);

    // 格式化日期为 月-日 格式（例如 09-25）
    // 注意：getMonth() 返回 0-11，所以需要 +1
    const year = String(selectedDate.getFullYear() + 1).padStart(2, '0');
    const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
    const day = String(selectedDate.getDate()).padStart(2, '0');
    const formattedDate = `${year}-${month}-${day}`;


    // 构建与后端模型完全匹配的预约数据
    const appointmentData = {
      customerId: userInfo.id?.toString().trim() || '',
      customerName: (userInfo.name || '未知用户').trim(),
      phone: userInfo.account?.toString().trim() || '',
      productId: serviceContent.length > 0
        ? serviceContent.map(s => s.productId?.toString().trim()).filter(Boolean)
        : [],
      packageId: (packageData.packageId || id)?.toString().trim() || '',
      time: baseTimeSlots[selectedTime]?.trim() || '',
      money: packageData.price ? Number(packageData.price) : 0,
      period: formattedDate
    };

    // 调用API
    const response = await add_appointment(appointmentData);

    if (response.code === 0) {
       message.success(response.message);
    } else {
       message.error(response.message);
    }
  };



  // 加载状态显示
  if (loading) {
    return <Loaging loadingText="加载套餐详情中..." />;
  }

  // 错误状态显示
  if (error || !packageData) {
    return <Error message={error || "未找到套餐信息"} />;
  }

  // 轮播图数据
  const carouselImages = packageData.photo
    ? packageData.photo.split(',').map(url => url.trim())
    : ['https://picsum.photos/id/177/800/500', 'https://picsum.photos/id/235/800/500'];

  // 适用人群数据
  const suitablePeople = packageData.suitablePeople || [
    { icon: '💻', text: '久坐办公族' },
    { icon: '📱', text: '低头手机族' },
    { icon: '📚', text: '长期学习者' },
    { icon: '🧑💼', text: '颈椎劳损者' },
    { icon: '😣', text: '肩颈酸痛者' }
  ];

  // 用户评价数据
  const reviews = packageData.reviews || [
    {
      id: 1,
      name: '张女士',
      avatar: 'https://picsum.photos/id/64/100/100',
      rating: 5,
      content: '师傅手法专业，做完之后明显轻松了很多，推荐！',
      date: '2023-10-15'
    },
    {
      id: 2,
      name: '李先生',
      avatar: 'https://picsum.photos/id/65/100/100',
      rating: 4,
      content: '效果不错，环境也很安静，周末人多需要提前预约',
      date: '2023-10-10'
    }
  ];

  // 渲染页面
  return (
    <div className="therapy-detail-page">
      <header className="detail-header">
        <ArrowLeftOutlined
          className="header-icon"
          style={{ color: '#8B5A2B', fontSize: '20px', cursor: 'pointer' }}
          onClick={() => navigate(-1)}
        />
        <h1 className="header-title">项目详情</h1>
        <div className="header-actions">
          <HeartOutlined
            className="header-icon"
            style={{ fontSize: '20px', color: isFavorite ? '#8b4513' : '#888' }}
            onClick={() => setIsFavorite(!isFavorite)}
          />
        </div>
      </header>

      <Carousel images={carouselImages} />

      <div className="project-basic">
        <div className="project-title-container">
          <h2 className="project-title">{packageData.name}</h2>
        </div>

        <div className="project-rating">
          <Rate
            icon={<StarOutlined style={{ color: '#ffc53d' }} />}
            defaultValue={packageData.rating || 4.9}
            disabled
            count={5}
            size="small"
          />
          <span className="rating-value">{packageData.rating || 4.9}</span>
          <span className="rating-count">({packageData.reviewCount || 128}人评价)</span>
          <span className="rating-good">{packageData.goodRate || 98}%好评</span>
        </div>

        <div className="project-price">
          <span className="current-price">¥{packageData.price}</span>
          {packageData.originalPrice && (
            <span className="original-price">¥{packageData.originalPrice}</span>
          )}
        </div>
      </div>

      <div className="project-info">
        <div className="info-row">
          <div className="info-item">
            <ClockCircleOutlined className="info-icon" style={{ fontSize: '16px', color: '#8b4513' }} />
            <span className="info-text">{packageData.duration || '90分钟'}</span>
          </div>
          <div className="info-item">
            <UserOutlined className="info-icon" style={{ fontSize: '16px', color: '#8b4513' }} />
            <span className="info-text">中医师1对1服务</span>
          </div>
          <div className="info-item">
            <EnvironmentOutlined className="info-icon" style={{ fontSize: '16px', color: '#8b4513' }} />
            <span className="info-text">本草轩理疗馆(总店)</span>
          </div>
        </div>
      </div>

      <div className="td_section-container">
        <h3 className="section-title">适用人群</h3>
        <SuitablePeople people={suitablePeople} />
      </div>

      <div className="td_section-container">
        <h3 className="section-title">服务内容</h3>
        <ServiceProcess
          steps={serviceContent}
          loading={serviceLoading}
          error={serviceError}
        />
        {serviceError && (
          <Button
            className="retry-service-btn"
            onClick={reloadServiceContent}
            style={{ marginTop: '10px' }}
          >
            重新加载服务内容
          </Button>
        )}
      </div>

      <div className="td_section-container">
        <h3 className="section-title">用户评价</h3>
        <div className="reviews-container">
          {reviews.map(review => (
            <div key={review.id} className="review-item">
              <img
                src={review.avatar}
                alt={review.name}
                className="review-avatar"
                onError={(e) => e.target.src = 'https://picsum.photos/id/1000/100/100'}
              />
              <div className="review-content">
                <div className="review-header">
                  <span className="review-name">{review.name}</span>
                  <Rate
                    icon={<StarOutlined style={{ color: '#ffc53d' }} />}
                    defaultValue={review.rating}
                    disabled
                    count={5}
                    size="small"
                  />
                </div>
                <p className="review-text">{review.content}</p>
                <span className="review-date">{review.date}</span>
              </div>
            </div>
          ))}
          <Button className="more-reviews" variant="outline">查看全部评价</Button>
        </div>
      </div>

      <div className="td_section-container">
        <h3 className="section-title">立即预约</h3>

        <div className="booking-options">
          <div className="date-selector">
            <h4 className="option-title">选择日期</h4>
            <div className="date-options">
              {dates.map((date, index) => (
                <button
                  key={index}
                  className={`date-btn ${selectedDateIndex === index ? 'selected' : ''}`}
                  onClick={() => handleDateSelect(index)}
                  disabled={date.isPast}
                >
                  <span className="date-weekday">{date.weekday}</span>
                  <span className="date-day">{date.day}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="time-selector">
            <h4 className="option-title">选择时间</h4>
            <div className="time-options">
              {availableTimeSlots.length > 0 ? (
                availableTimeSlots.map((time, index) => {
                  const originalIndex = baseTimeSlots.indexOf(time);
                  return (
                    <button
                      key={originalIndex}
                      className={`time-btn ${selectedTime === originalIndex ? 'selected' : ''}`}
                      onClick={() => handleTimeSelect(originalIndex)}
                    >
                      {time}
                    </button>
                  );
                })
              ) : (
                <div className="no-time-slots">
                  该日期暂无可用时段，请选择其他日期
                </div>
              )}
            </div>
          </div>
        </div>

        <Button
          className="book-now-btn"
          disabled={!canBook || bookingLoading}
          style={{
            backgroundColor: canBook ? '#8b4513' : '#c2a68e',
            color: '#fff',
            width: '100%',
            height: '50px',
            fontSize: '16px',
            marginTop: '20px'
          }}
          onClick={handleConfirmBooking}
        >
          {bookingLoading ? (
            <>
              <LoadingOutlined style={{ marginRight: 8 }} />
              预约中...
            </>
          ) : (
            `立即预约 - ¥${packageData.price}`
          )}
        </Button>
      </div>
    </div>
  );
};

export default ProjectDetail;
